package com.browan.constellation;

import java.util.List;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.DialogInterface.OnClickListener;
import android.content.SharedPreferences.Editor;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.view.ContextMenu;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ContextMenu.ContextMenuInfo;
import android.widget.ProgressBar;
import android.widget.SimpleCursorAdapter;
import android.widget.TextView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import com.browan.constellation.configuration.Configuration;
import com.browan.constellation.configuration.ResourceURL;
import com.browan.constellation.data.RSSData;
import com.browan.constellation.db.DbHelper;
import com.browan.constellation.http.HttpClient;
import com.browan.constellation.util.NetWorkUtil;
import com.browan.constellation.util.Util;

public class RssConstellation extends ListActivity
{
	private ProgressBar m_progressBar;

	private TextView tv;

	private Cursor cursor;

	private DbHelper m_dbHelper;

	private String m_Update_Time;

	public static String RSS_UPDATE_TIME = "rss_date_time";

	private SharedPreferences sharedPreferences;

	private SimpleCursorAdapter adapter;

	private String current_time = Util.getDate();

	@Override
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.rss_main);

		m_progressBar = (ProgressBar) findViewById(R.id.progressbar);

		tv = (TextView) findViewById(android.R.id.empty);

		getListView().setOnCreateContextMenuListener(this);

		sharedPreferences = getSharedPreferences(Configuration.RSS_FILE_NAME, MODE_PRIVATE);

		m_Update_Time = sharedPreferences.getString(RSS_UPDATE_TIME, null);
		m_dbHelper = new DbHelper(this);

		RSSData.CURRENT_RSS_UPTIME = m_Update_Time;

		cursor = m_dbHelper.getItemCurson(m_Update_Time);

		adapter = new SimpleCursorAdapter(this, R.layout.rss_item, cursor, new String[] { RSSData.ITEM_TITLE,
				RSSData.ITEM_DESC, RSSData.ITEM_PUBDATE }, new int[] { R.id.title, R.id.content, R.id.pub_date });
		setListAdapter(adapter);

		if (current_time.equals(m_Update_Time))
		{
			m_progressBar.setVisibility(View.GONE);
		}
		else
		{
			doGetData();
		}

		if (cursor.getCount() > 0)
		{
			m_progressBar.setVisibility(View.GONE);
		}

	}

	private void doGetData()
	{
		if (NetWorkUtil.isLive(this))
		{
			new Thread(loadData).start();
		}
		else
		{
			doNoNetWork();
		}
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo)
	{
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.setHeaderTitle("操作");
		menu.add(0, Menu.FIRST, 0, "分享");
		menu.add(0, Menu.FIRST + 1, 0, "收藏");
	}

	@Override
	public boolean onContextItemSelected(MenuItem item)
	{
		int selectedPosition = ((AdapterContextMenuInfo) item.getMenuInfo()).position;
		Cursor cursor = (Cursor) adapter.getItem(selectedPosition);

		boolean ret = true;

		switch (item.getItemId())
		{
		case Menu.FIRST:
			Intent intent = new Intent(Intent.ACTION_SEND);
			intent.setType("text/plain");
			intent.putExtra(Intent.EXTRA_SUBJECT, cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_TITLE)));
			intent.putExtra(Intent.EXTRA_TEXT, cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_DESC))
					+ "\n\n" + cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_LINK)));
			startActivity(Intent.createChooser(intent, getTitle()));

			break;

		case Menu.FIRST + 1:
			m_dbHelper.historyItem(cursor.getInt(cursor.getColumnIndexOrThrow(RSSData._ID)));
			break;

		default:
			ret = super.onContextItemSelected(item);
			break;
		}
		return ret;
	}

	private void doNoNetWork()
	{
		m_progressBar.setVisibility(View.GONE);
		tv.setText("没有网络");
	}

	Runnable loadData = new Runnable()
	{

		@Override
		public void run()
		{
			HttpClient client = new HttpClient();
			String xmlContent;
			try
			{
				xmlContent = client.getMethod(ResourceURL.RSS_URL, ResourceURL.RSS_ENCODING);
				List<RSSData> list = RSSParser.parseUrl(xmlContent);
				if (!RSSData.CURRENT_RSS_UPTIME.equals(m_Update_Time))
				{
					m_dbHelper.updateRssItem(list);
					handler.sendEmptyMessage(0);
				}
			}
			catch (Exception e)
			{
				e.printStackTrace();
				handler.sendEmptyMessage(1);
			}

		}
	};

	protected void onResume()
	{
		adapter.notifyDataSetChanged();
		super.onResume();
	};

	Handler handler = new Handler()
	{
		public void handleMessage(android.os.Message msg)
		{
			super.handleMessage(msg);
			m_progressBar.setVisibility(View.GONE);
			switch (msg.what)
			{
			case 0:
				if (null != cursor)
				{
					cursor.close();
					cursor = null;
				}
				cursor = m_dbHelper.getItemCurson(RSSData.CURRENT_RSS_UPTIME);
				adapter = new SimpleCursorAdapter(RssConstellation.this, R.layout.rss_item, cursor, new String[] {
						RSSData.ITEM_TITLE, RSSData.ITEM_DESC, RSSData.ITEM_PUBDATE }, new int[] { R.id.title,
						R.id.content, R.id.pub_date });
				setListAdapter(adapter);
				Editor editor = sharedPreferences.edit();

				editor.putString(RSS_UPDATE_TIME, RSSData.CURRENT_RSS_UPTIME);

				editor.commit();
				break;
			case 1:
				tv.setText("获取数据发生错误!");
				break;

			default:
				break;
			}

		};

	};

	protected void onListItemClick(android.widget.ListView l, android.view.View v, int position, long id)
	{

		// Intent intent = new Intent(this, Detial.class);
		// intent.setData(Uri.parse(list.get(position).getLink()));
		// startActivity(intent);

		// http://www.google.com/gwt/x?gwt=on&u=

		// startActivity(new Intent(Intent.ACTION_VIEW,
		// Uri.parse(list.get(position).getLink())));

		Cursor cursor = (Cursor) adapter.getItem(position);

		// startActivity(new Intent(Intent.ACTION_VIEW,
		// Uri.parse("http://www.google.com/gwt/x?gwt=on&u="
		// +
		// cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_LINK)))));

		String title = cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_TITLE));

		String message = cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_DESC));

		final String link = cursor.getString(cursor.getColumnIndexOrThrow(RSSData.ITEM_LINK));

		if (TextUtils.isEmpty(message))
		{
			startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
		}
		else
		{

			AlertDialog dialog = new AlertDialog.Builder(this).setTitle(title).setMessage(message).setPositiveButton(
					"查看", new DialogInterface.OnClickListener()
					{
						@Override
						public void onClick(DialogInterface dialog, int which)
						{
							startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(link)));
						}
					}).setNegativeButton("取消", null).create();
			dialog.show();
		}

	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event)
	{
		if (keyCode == KeyEvent.KEYCODE_BACK)
		{
			exitDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean isExit;

	protected boolean exitDialog()
	{
		isExit = true;
		new AlertDialog.Builder(this).setTitle("退出").setMessage("确定退出程序？").setPositiveButton("是", new OnClickListener()
		{
			@Override
			public void onClick(DialogInterface dialog, int which)
			{
				RssConstellation.this.finish();
			}
		}).setNegativeButton("否", null).setCancelable(false).create().show();
		return isExit;
	};

	@Override
	protected void onDestroy()
	{
		if (null != cursor)
		{
			cursor.close();
			cursor = null;
		}
		m_dbHelper.close();

		super.onDestroy();
	}

}